<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('pageNetwork.table.addIpv4Address')"
    width="500"
  >
    <el-form ref="hostNameFormRef" :model="form" :rules="rules">
      <el-form-item :label="$t('pageNetwork.modal.ipAddress')" prop="ipAddress">
        <el-input v-model="form.ipAddress" />
      </el-form-item>
      <el-form-item :label="$t('pageNetwork.modal.gateway')" prop="gateway">
        <el-input v-model="form.gateway" />
      </el-form-item>
      <el-form-item
        :label="$t('pageNetwork.modal.subnetMask')"
        prop="subnetMask"
      >
        <el-input v-model="form.subnetMask" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">
          {{ $t('global.action.cancel') }}
        </el-button>
        <el-button type="primary" @click="onOk">
          {{ $t('global.action.add') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useVuelidateTool from '@/hooks/useVuelidateTool';
const { useVuelidate, required, ipAddress, elementInputValidator } =
  useVuelidateTool();

const dialogVisible = ref(false);
const form = reactive({ ipAddress: '', gateway: '', subnetMask: '' });
const hostNameFormRef = ref();
const emit = defineEmits(['ok']);

const props = defineProps<{ defaultGateway: string }>();

// Set vuelidate rules.
const v$ = useVuelidate(
  {
    ipAddress: { required, ipAddress },
    gateway: { required, ipAddress },
    subnetMask: { required, ipAddress },
  },
  form,
);

// validators
const rules = computed(() => {
  return {
    ipAddress: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'hostnipAddressame'),
      },
    ],
    gateway: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'hostnipAddressame'),
      },
    ],
    subnetMask: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'hostnipAddressame'),
      },
    ],
  };
});

const handleSubmit = () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  emit('ok', {
    Address: form.ipAddress,
    Gateway: form.gateway,
    SubnetMask: form.subnetMask,
  });
  closeModal();
};

const closeModal = () => {
  nextTick(() => {
    dialogVisible.value = false;
  });
};

const resetForm = () => {
  form.ipAddress = '';
  form.gateway = props.defaultGateway;
  form.subnetMask = '';
  v$.value.$reset();
  closeModal();
};

const onOk = async () => {
  handleSubmit();
};

defineExpose({
  dialogVisible,
});

watch(
  () => props.defaultGateway,
  () => {
    form.gateway = props.defaultGateway;
  },
);
</script>
